package com.domino.client.view;

import com.domino.client.mvc.View;
import com.domino.client.mvc.ViewUpdateCallback;
import com.domino.shared.SessionStateResponse;
import com.domino.shared.model.Brick;
import com.domino.shared.model.Color;

public class BoardViewCallbackHandler implements ViewUpdateCallback {
	
	private View view;

	BoardViewCallbackHandler(View view) {
		this.view = view;
	}
	
	@Override
	public void notify(SessionStateResponse sessionState) {
		if (sessionState.getSessionId()!=null) 
		{
			view.notifyNewSessionId(sessionState.getSessionId());
		}
		if (sessionState.getColor()!=null) 
		{
			view.notifyColor(sessionState.getColor());
		}
		if (sessionState.getPlayer()!=null) 
		{
			view.notifyPlayer(sessionState.getPlayer());
		}
		if (sessionState.getOpponent()!=null) 
		{
			view.notifyOpponent(sessionState.getOpponent());
		}
		if (sessionState.getMoves()!=null) 
		{
			for(Brick b : sessionState.getMoves()) {
				view.notifyMove(b);
			}
		}
		if (sessionState.makeAMove()==true) 
		{
			boolean bugDetected = view.notifyMakeAmove();
			if (bugDetected==true) {
				view.debug("SuperFulis: " + sessionState);
			}
		} 
		else if (sessionState.recoveringFromError()==true) 
		{
			view.notifyError("A recoverable error occurred");
		} 
		else if (sessionState.waitForOppponentAction()==true){
			view.notifyWaitOpponentAction();
		} 
		else if (sessionState.waitForServer()==true) {
			view.notifyWaitForServer();
		}
		else if (sessionState.isFinished()==true) 
		{
			view.notifyGameFinished();
		} else {
			view.debug("Unexpected state " + sessionState);
		}
		if (sessionState.getDebugMessage()!=null) {
			view.debug("Debug message: " + sessionState.getDebugMessage());
		}
		if (sessionState.getGivingUpColor()!=null) {
			view.notifyPlayerGaveUp(sessionState.getGivingUpColor());
		}
		view.debug(sessionState.toString());
	}

	@Override
	public void notifyError(boolean recoverable, String localizedMessage) {
		view.notifyError(recoverable?"Unexpected error, will try to recover":"Unexpected error, please restart client<br>" + localizedMessage);
		view.debug("ERROR : " + localizedMessage);
	}

	@Override
	public void notifyPlayerGaveUp(Color givingUpColor) {
		view.notifyPlayerGaveUp(givingUpColor);
	}

}
